class_name Fog
extends Sprite2D

#这个战争迷雾，不会隐藏其他npc，需要在npc的里面额外增加代码。一个思路是通过设置npc的透明度，
#距离玩家太远就不会显示即可


@export var fog_wight : int
@export var fog_height: int 
@export var light_texture:Texture2D


var player_list :Array[CharacterBody2D] = []
var player_dictionary_position: Dictionary[String, Vector2] = {}



var fog_image : Image
var fog_texture : ImageTexture
var light_image :Image

var current_image: Image
var current_texture: ImageTexture


func _ready() -> void:
	fog_image = Image.create(fog_wight,fog_height,false,Image.FORMAT_RGBA8)
	fog_image.fill(Color.WHITE)
	fog_texture = ImageTexture.create_from_image(fog_image)
	texture = fog_texture
	
	
	current_image = fog_image.duplicate()
	current_texture = fog_texture.duplicate()
	material.set_shader_parameter("current_texture",current_texture)
	
	light_image = light_texture.get_image()
	update_fog()



func add_player(player:CharacterBody2D):
	player_list.append(player)
	update_fog_one(player)



func _process(delta: float) -> void:
	
	for player in player_list :
		if !player_dictionary_position.has(player.name):
			update_fog_one(player)
			player_dictionary_position[player.name] = player.position


		
		if player_dictionary_position.has(player.name) && player_dictionary_position[player.name].distance_to(player.position)>3:
			update_fog_one(player)
			player_dictionary_position[player.name] = player.position


func update_fog():
	for player in player_list :
		update_fog_one(player)
	
func update_fog_one(player:CharacterBody2D):
	#var player_position = player.global_position-global_position + Vector2(light_image.get_width(),light_image.get_height())
	var player_position = player.global_position-global_position + Vector2(fog_wight,fog_height)/2
	player_position -= Vector2(light_image.get_size())/2.0
	fog_image.blend_rect(light_image,Rect2i(Vector2.ZERO,light_image.get_size()),player_position)
	
	fog_texture.update(fog_image)
	
	current_image.fill(Color.WHITE)
	current_image.blend_rect(light_image,Rect2i(Vector2.ZERO,light_image.get_size()),player_position)
	current_texture.update(current_image)
	
	
